package com.java.hohenheim.springplatform.web.service.login;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.spring.SpringUtil;
import com.java.hohenheim.springplatform.data.model.account.LoginParams;
import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import com.java.hohenheim.springplatform.db.entity.AccountThirdAuthsEntity;
import com.java.hohenheim.springplatform.db.mapper.AccountMapper;
import com.java.hohenheim.springplatform.db.mapper.AccountThirdAuthsMapper;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.exception.PlatformException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

/**
 * @author Hohenheim
 * @date 2020/8/13
 * @description
 */
public abstract class BaseLogin implements ILogin {
    @Autowired
    private AccountMapper mAccountMapper;
    @Autowired
    private AccountThirdAuthsMapper mThirdAccountMapper;

    /**
     * 根据第三方平台创建账户
     * @param accountEntity 账户信息
     * @param thirdEntity 第三方平台信息
     */
    protected boolean addThirdPlatformAccount(AccountEntity accountEntity, AccountThirdAuthsEntity thirdEntity) {
        PlatformTransactionManager platformTransactionManager = SpringUtil.getBean(PlatformTransactionManager.class);
        TransactionDefinition transaction = SpringUtil.getBean(TransactionDefinition.class);

        boolean addResult = false;
        TransactionStatus transactionStatus = null;

        try {
            transactionStatus = platformTransactionManager.getTransaction(transaction);

            addResult = mAccountMapper.insertSelective(accountEntity) > 0;
            if(addResult) {
                addResult = mThirdAccountMapper.insertSelective(thirdEntity) > 0;
            }

            if(addResult) {
                platformTransactionManager.commit(transactionStatus);
            }
            else {
                platformTransactionManager.rollback(transactionStatus);
            }
        }
        catch (Exception e) {
            addResult = false;

            if(null != transactionStatus) {
                platformTransactionManager.rollback(transactionStatus);
            }
        }

        return addResult;
    }

    protected void checkAccountAndPwdIsBlank(LoginParams param) {
        if(StringUtils.isBlank(param.getAccount()) || StringUtils.isBlank(param.getPassword())) {
            throw new PlatformException(ResultCodes.NAME_PWD_MUST_NOT_EMPTY);
        }
    }
}
